<template>
  <div class="home-container">
    <div class="cart-container">
      <div class="cart-title">
        <div class="logo">
          <img class="avatar" src="@/assets/cashierImages/avatar.png"/>
        </div>
        <div class="member-info">
          <span class="name" v-if="memberInfo">
            {{ memberInfo.mobile }}
          </span>
          <span class="none" v-if="!memberInfo">当前为非会员</span>
        </div>
      </div>
      <ul class="cart-list" v-if="cartList.length > 0">
        <li
          class="cart-item"
          v-for="cartInfo in cartList"
          :key="cartInfo.cartId"
        >
          <div class="cart-item-header">
            <img class="cart-image" :src="cartInfo.picUrl"/>
            <div class="cart-name">
              <div class="name" :title="cartInfo.goodsName">
                名称：{{ cartInfo.goodsName }}
              </div>
              <div class="code" :title="cartInfo.barCode">
                条形码：{{ cartInfo.barCode }}
              </div>
              <div class="spec" v-if="cartInfo.specifications">
                <span class="item" :title="cartInfo.specifications">
                  {{ cartInfo.specifications }}
                </span>
              </div>
            </div>
            <el-button
              plain
              size="mini"
              type="primary"
              icon="el-icon-delete"
              class="cart-delete"
              @click="removeFromCart(cartInfo)"
            ></el-button>
          </div>
          <div class="cart-item-option">
            <el-input-number
              class="input"
              @change="changeBuyNum(cartInfo)"
              v-model="cartInfo.number"
              :min="1"
              :max="1000"
            />
            <priceItem :goodsItem="cartInfo"></priceItem>
          </div>
        </li>
      </ul>
      <div class="empty" v-if="cartList.length == 0">
        <el-empty description="暂无结算商品" :image-size="40"></el-empty>
      </div>
      <!-- </div> -->
      <div class="footer">
        <div class="number">
          <div class="total-num">
            商品件数：<b class="num"> {{ cartTotalNum }}</b>
          </div>
          <div class="total-price">
            商品总价：<b class="num"
          >￥{{
              checkedAllGoodsAmount
                ? checkedAllGoodsAmount.toFixed(2)
                : "0.00"
            }}</b
          >
          </div>
          <div class="total-price">
            优惠金额：<b class="num"
          >￥{{
              checkedAllGoodsAmount - cartTotalPrice
                ? (checkedAllGoodsAmount - cartTotalPrice).toFixed(2)
                : "0.00"
            }}</b
          >
          </div>
          <div class="total-price">
            支付金额：<b class="num"
          >￥{{ cartTotalPrice ? cartTotalPrice.toFixed(2) : "0.00" }}</b
          >
          </div>
        </div>
        <el-button
          :disabled="cartTotalNum == 0"
          type="danger"
          plain
          class="main-button"
          @click="doSettlement()"
        >
          提交结算
        </el-button>
      </div>
    </div>
    <div class="main-list">
      <div class="search-box">
        <el-form
          class="search-form"
          ref="searchForm"
          :inline="true"
          :model="searchForm"
        >
          <el-form-item class="form-item" label="" prop="keyword">
            <el-input
              v-model="searchForm.keyword"
              prefix-icon="el-icon-full-screen"
              @keyup.enter.native="doQueryGoods"
              @input="doQueryGoods"
              class="input-item"
              placeholder="请输入商品关键字：名称、条码"
              clearable
              maxlength="100"
              ref="inputRef"
            />
          </el-form-item>
          <el-button
            class="search-goods"
            @click="doQueryGoods()"
            icon="el-icon-search"
          >查询商品
          </el-button>
          <el-button
            class="search-goods"
            icon="el-icon-refresh"
            @click="switchMember('switch')"
            v-if="memberInfo == null"
          >
            关联会员
          </el-button>
          <el-button
            class="search-goods"
            icon="el-icon-refresh"
            @click="doSwitchMember(null)"
            v-if="memberInfo != null"
          >
            切换为非会员
          </el-button>
          <el-button
            class="search-goods"
            icon="el-icon-refresh"
            @click="switchMember('add')"
          >
            添加会员
          </el-button>
          <el-button
            class="search-goods"
            icon="el-icon-refresh"
            @click="switchHeXiao()"
          >
            优惠券核销
          </el-button>
          <!--          <el-form-item class="setting">-->
          <!--            <span-->
          <!--              :class="goodsMode == 'small' ? 'item active' : 'item'"-->
          <!--              @click="switchGoodMode('small')"-->
          <!--            >-->
          <!--              <svg-->
          <!--                t="1741317847001"-->
          <!--                class="icon"-->
          <!--                viewBox="0 0 1024 1024"-->
          <!--                version="1.1"-->
          <!--                xmlns="http://www.w3.org/2000/svg"-->
          <!--                p-id="6842"-->
          <!--                width="16"-->
          <!--                height="16"-->
          <!--              >-->
          <!--                <path-->
          <!--                  d="M263.104 760.896V960H64v-199.104h199.104z m348.48 0V960H412.416v-199.104h199.168z m348.416 0V960h-199.104v-199.104H960zM263.104 412.416v199.168H64V412.416h199.104z m348.48 0v199.168H412.416V412.416h199.168z m348.416 0v199.168h-199.104V412.416H960zM263.104 64v199.104H64V64h199.104z m348.48 0v199.104H412.416V64h199.168zM960 64v199.104h-199.104V64H960z"-->
          <!--                  p-id="6843"-->
          <!--                ></path>-->
          <!--              </svg>-->
          <!--              <span class="text">小图</span>-->
          <!--            </span>-->
          <!--            <span-->
          <!--              :class="goodsMode == 'big' ? 'item active' : 'item'"-->
          <!--              @click="switchGoodMode('big')"-->
          <!--            >-->
          <!--              <svg-->
          <!--                t="1741318028632"-->
          <!--                class="icon"-->
          <!--                viewBox="0 0 1024 1024"-->
          <!--                version="1.1"-->
          <!--                xmlns="http://www.w3.org/2000/svg"-->
          <!--                p-id="2278"-->
          <!--                width="16"-->
          <!--                height="16"-->
          <!--              >-->
          <!--                <path-->
          <!--                  d="M934.4 934.4V633.6H633.6v300.8h300.8m-544 0V633.6H89.6v300.8h300.8m544-544V89.6H633.6v300.8h300.8m-544 0V89.6H89.6v300.8h300.8M960 1024H608a64 64 0 0 1-64-64V608a64 64 0 0 1 64-64H960a64 64 0 0 1 64 64V960a64 64 0 0 1-64 64z m-544 0H64a64 64 0 0 1-64-64V608a64 64 0 0 1 64-64h352a64 64 0 0 1 64 64V960a64 64 0 0 1-64 64zM960 480H608a64 64 0 0 1-64-64V64a64 64 0 0 1 64-64H960a64 64 0 0 1 64 64v352a64 64 0 0 1-64 64z m-544 0H64a64 64 0 0 1-64-64V64a64 64 0 0 1 64-64h352a64 64 0 0 1 64 64v352a64 64 0 0 1-64 64z"-->
          <!--                  fill="#333333"-->
          <!--                  p-id="2279"-->
          <!--                ></path>-->
          <!--              </svg>-->
          <!--              <span class="text">大图</span>-->
          <!--            </span>-->
          <!--          </el-form-item>-->
        </el-form>
        <el-tabs
          class="tab-box"
          type="card"
          v-model="catalogTab"
          @tab-click="switchCatalog"
        >
          <el-tab-pane label="全部" name=""></el-tab-pane>
          <el-tab-pane
            v-for="catalog in catalogList"
            :label="catalog.name"
            :key="catalog.id + ''"
            :name="catalog.id + ''"
          ></el-tab-pane>
        </el-tabs>
      </div>
      <div class="goods-list">
        <div
          class="goods-item"
          v-for="goodsInfo in goodsList"
          :key="goodsInfo.id"
        >
          <div class="item" @click="clickGoods(goodsInfo)">
            <img class="image" lazy :src="goodsInfo.picUrl"/>
            <div class="goods-name">{{ goodsInfo.name }}</div>
            <priceItem :goodsItem="goodsInfo"></priceItem>
          </div>
        </div>
        <pagination
          v-show="totalGoods > 0"
          :total="totalGoods"
          class="pagination"
          :page.sync="page"
          :limit.sync="pageSize"
          :prevText="'上一页'"
          :nextText="'下一页'"
          @pagination="initGoodsList"
        />

        <el-empty
          v-if="goodsList.length == 0"
          description="暂无商品..."
        ></el-empty>
      </div>
    </div>

    <!-- 规格详情 start-->
    <el-dialog
      title="选择商品规格"
      :visible.sync="openGoodsDialog"
      class="common-dialog"
      append-to-body
    >
      <div class="goods-info">
        <div class="name">{{ goodsInfo.name }}</div>
        <priceItem class="price" :goodsItem="goodsInfo"></priceItem>
        <div class="num">
          <el-input-number
            class="input"
            v-model="goodsNum"
            :min="1"
            :max="1000"
          />
        </div>
        <div class="spec-list" v-if="goodsInfo.specList.length">
          <div
            class="spec-item"
            v-for="specInfo in goodsInfo.specList"
            :key="specInfo.name"
          >
            <div class="spec-name">{{ specInfo.name }}</div>
            <div class="values">
              <div
                v-for="child in specInfo.valueList"
                :key="child.id"
                :class="
                  specifications.includes(child.value)
                    ? 'value active'
                    : 'value'
                "
                @click="selectGoodsSpec(child.value)"
              >
                {{ child.value }}
              </div>
              <div style="clear: both"></div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="main-button" @click="addToCart()">
          加入结算
        </el-button>
        <el-button @click="closeGoodsDialog()">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 规格详情 end-->

    <!--关联/添加会员对话框 start-->
    <switchMemberDialog
      :action-type="actionType"
      :show-dialog="openMemberDialog"
      @doSwitchMember="doSwitchMember"
      @closeMemberDialog="closeMemberDialog"
    />
    <!--关联会员对话框 end-->

    <!--HeXiao start-->
    <UserWriteOffDialog
      :show-dialog="openHeXiaoDialog"
      @closeHeXiaoDialog="closeHeXiaoDialog"
    />
    <!--HeXiao end-->

    <!--结算对话框 start-->
    <settlementDialog
      :show-dialog="openSettlementDialog"
      :memberInfo="memberInfo"
      :totalPrice="cartTotalPrice"
      :remarks="cartRemark"
      :orderInfo="orderInfo"
      @submit="submitSettlement"
      @switchMember="switchMember"
      @closeDialog="closeDialog"
    />
    <!--结算对话框 end-->

    <!--扫码付款对话框 start-->
    <!-- <scanPayCodeDialog
        ref="scanPayCodeDialog"
        :show-dialog="openScanPayCodeDialog"
        :memberInfo="memberInfo"
        :orderId="orderId"
        :payType="payType"
        :payAmount="payAmount"
        @closeDialog="closeDialog"
        @showPayResult="showPayResult"
      /> -->
    <!--扫码付款对话框 end-->

    <!--支付结果对话框 start-->
    <payResultDialog
      :show-dialog="openPayResultDialog"
      :payResult="payResult"
      @showOrderPrint="showOrderPrint"
      @closeDialog="closeDialog"
    />
    <!--支付结果对话框 end-->

    <!--打印订单对话框 start-->
    <orderPrintDialog
      :show-dialog="openOrderPrintDialog"
      :storeName="storeName"
      :orderInfo="orderInfo"
      :orderGoods="orderGoods"
      @closeDialog="closeDialog"
    />
    <!--打印订单对话框 end-->

    <!-- 无商品收款组件 start-->
    <noGoodsCashier
      :show-dialog="openNoGoodsCashierDialog"
      @submit="submitCashier"
      @closeDialog="closeDialog"
    >
    </noGoodsCashier>
    <!-- 无商品收款组件 end-->

  </div>
</template>

<script>
import { getOrderInfo, submitOrder, transmitNotify } from "@/api/cashier/order"
import { getCatalogList } from "@/api/cashier/catalog"
import { getGoodsDetail, getGoodsList } from "@/api/cashier/goods"
import { cartAdd, cartDelete, cartUpdate, getCartInfo, updateCartVip } from "@/api/cashier/cart"
import { getMobile, getUserId, removeMobile, removeUserId, setMobile, setUserId } from "@/utils/auth"
import switchMemberDialog from "./components/switchMemberDialog"
import settlementDialog from "./components/settlementDialog"
import scanPayCodeDialog from "./components/scanPayCodeDialog"
import payResultDialog from "./components/payResultDialog"
import orderPrintDialog from "./components/orderPrintDialog"
import noGoodsCashier from "./components/noGoodsCashier"
import priceItem from "./components/priceItem"
import Pagination from "@/components/Pagination"
import { getMemberInfo } from "@/api/cashier/member"
import userWriteOffDialog from "./components/userWriteOffDialog"
import UserWriteOffDialog from "@/views/cashier/home/components/userWriteOffDialog"

export default {
  name: "Cashier",
  components: {
    UserWriteOffDialog,
    switchMemberDialog,
    settlementDialog,
    scanPayCodeDialog,
    payResultDialog,
    orderPrintDialog,
    noGoodsCashier,
    priceItem,
    Pagination
  },
  data() {
    return {
      // 导航tab
      catalogTab: "",
      isOpen: true,
      page: 1,
      pageSize: 24,
      totalGoods: 0,
      openGoodsDialog: false,
      openMemberDialog: false,
      openSettlementDialog: false,
      openNoGoodsCashierDialog: false,
      // openScanPayCodeDialog: false,
      openPayResultDialog: false,
      openOrderPrintDialog: false,
      openHeXiaoDialog: false,
      searchForm: { keyword: "" },
      payResult: { isSuccess: false, payAmount: 0, orderId: 0 },
      goodsForm: {},
      // 激活菜单
      activeMenu: "cashier",
      // 分类类目
      catalogList: [],
      // 当前操作会员
      memberInfo: null,
      actionType: "",
      // 当前登录用户
      accountName: this.$store.getters.name,
      // 当前门店信息
      storeName: this.$store.getters.storeName,
      // 当前操作商品
      goodsInfo: { num: 1, specList: [], productList: [] },
      // 当前选择属性
      specifications: [],
      // 商品数量
      goodsNum: 1,
      // 当前分类
      categoryId: "",
      // 商品分类列表
      cateList: [],
      // 商品列表
      goodsList: [],
      // 购物车列表
      cartList: [],
      // 总金额
      cartTotalPrice: 0,
      // 购物车备注
      cartRemark: "",
      // 总件数
      cartTotalNum: 0,
      //原价
      checkedAllGoodsAmount: 0,
      // 支付金额
      payAmount: 0,
      // 当前订单号
      orderId: 0,
      // 支付方式
      // 支付方式1现金2微信3支付宝4银行卡5赊账
      payType: "1",
      // 当前订单
      orderInfo: {},
      orderGoods: [],
      isSearch: false,
      timeoutId: null
    }
  },
  mounted() {
    const app = this
    // 监听扫码枪按键
    let code = ""
    let lastTime, nextTime // 上次时间、最新时间
    let lastCode, nextCode // 上次按键、最新按键
    document.onkeypress = (e) => {
      // 获取按键
      if (window.event) {
        // IE
        nextCode = e.keyCode
      } else if (e.which) {
        // Netscape/Firefox/Opera
        nextCode = e.which
      }
      // 如果触发了回车事件(扫码结束时间)
      if (nextCode === 13) {
        this.$nextTick(() => {
          this.$refs.inputRef.focus()
        })
        if (code.length < 3) {
          return
        }
        // if (app.openScanPayCodeDialog == true) {
        //   app.$refs.scanPayCodeDialog.submit(code);
        //   return false;
        // }
        if (app.openMemberDialog == true) {
          return false
        }
        if (app.openSettlementDialog == true) {
          app.$alert("请点击确定收款！")
          return false
        }
        console.log(app.activeMenu)
        if (app.activeMenu == "cashier") {
          app.addToCart1(code)
        }
        code = ""
        lastCode = ""
        lastTime = ""
        return true
      }
      nextTime = new Date().getTime() // 记录最新时间
      if (!lastTime && !lastCode) {
        // 如果上次时间和上次按键为空
        code += e.key // 执行叠加操作
      }
      // 如果有上次时间及上次按键
      if (lastCode && lastTime && nextTime - lastTime > 30) {
        code = e.key
      } else if (lastCode && lastTime) {
        code += e.key
      }
      lastCode = nextCode
      lastTime = nextTime
      return true
    }
  },
  created() {
    this.initCatalog()
    this.initGoodsList()
    let userId = getUserId()
    if (userId && userId != undefined) {
      this.memberInfo = {
        mobile: getMobile(),
        vipUserId: getUserId()
      }
      console.log(this.memberInfo)
      this.getVipInfo(getMobile())
      updateCartVip({ vipUserId: getUserId() || "" }).then(() => {
      })
    }
    this.getCartList()
    this.$nextTick(() => {
      this.$refs.inputRef.focus()
    })
    setInterval(this.getTransmitOrders, 60000)
    this.getTransmitOrders()
  },
  methods: {
    // 初始化分类
    initCatalog() {
      getCatalogList().then((response) => {
        this.catalogList = response.data.data?.categoryList || []
      })
    },
    // 初始化商品列表
    initGoodsList(option) {
      if (option && option.limit) {
        this.pageSize = option.limit
      }
      getGoodsList({
        brandId: this.$store.getters.storeId,
        categoryId: this.categoryId,
        page: this.page,
        size: this.pageSize,
        keyword: this.searchForm.keyword
      })
        .then((response) => {
          this.goodsList = response.data.data?.goodsList || []
          this.totalGoods = response.data.data?.count || 0
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
          console.log(err.toString())
        })
    },
    // 菜单切换
    switchMenu(menuKey) {
      this.activeMenu = menuKey
      if (menuKey == "logout") {
        this.$store.dispatch("LogOut").then(() => {
          location.reload() // In order to re-instantiate the vue-router object to avoid bugs
        })
      }
      return menuKey
    },
    // tab切换
    switchCatalog(el) {
      this.catalogTab = el.name
      this.filterCate(this.catalogTab)
    },
    // 过滤分类商品
    filterCate(categoryId) {
      this.categoryId = categoryId
      this.initGoodsList()
    },
    // 购物车信息
    getCartList() {
      if (this.loading) {
        return false
      }
      this.loading = true
      this.cartList = []
      getCartInfo({
        userId: this.$store.getters.userId
      })
        .then((response) => {
          response.data.data.brandCartGoods.forEach((brandCarts) => {
            brandCarts.cartList.forEach((cartInfo) => {
              this.cartList.push({
                ...cartInfo,
                cartId: cartInfo.id,
                retailPrice: cartInfo.price,
                specifications: cartInfo?.specifications.join("-") || ""
              })
            })
          })
          this.cartTotalPrice = response.data.data.cartTotal.goodsAmount
          this.cartTotalNum = response.data.data.cartTotal.goodsCount
          this.checkedAllGoodsAmount =
            response.data.data.cartTotal.checkedAllGoodsAmount
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
          console.log(err.toString())
        })
    },
    // 查询商品
    doQueryGoods() {
      const app = this
      app.initGoodsList()
      // if (!app.searchForm.keyword) {
      //   return false
      // }
      // app.loading = true
      // getGoodsList({ keyword: app.searchForm.keyword })
      //   .then((response) => {
      //     app.loading = false
      //     if (response.data.data && response.data.data.length > 0) {
      //       app.goodsList = response.data.data
      //     } else {
      //       app.$alert("抱歉，未查询到商品信息！")
      //       return false
      //     }
      //   })
      //   .catch((err) => {
      //     app.loading = false
      //     console.log(err.toString())
      //   })
    },
    // 点击商品规格弹框
    clickGoods(goodsInfo) {
      if (this.loading) {
        return false
      }
      this.loading = true
      getGoodsDetail({
        id: goodsInfo.id,
        seckillId: 0
      })
        .then((response) => {
          console.log(1111, response)
          this.goodsInfo = response.data.data.info
          this.goodsInfo.specList = response.data.data.specificationList || []
          this.goodsInfo.productList = response.data.data.productList || []

          this.goodsNum = 1
          this.loading = false
          if (this.goodsInfo.productList?.length < 2) {
            this.addToCart(false)
          } else {
            this.openGoodsDialog = true
          }
        })
        .catch((err) => {
          this.loading = false
          console.log(err.toString())
        })
    },
    // 关闭规格弹框
    closeGoodsDialog() {
      this.openGoodsDialog = false
    },
    // 选择商品属性
    selectGoodsSpec(specValue) {
      let specValues = []
      this.goodsInfo.specList.forEach(() => {
        specValues.push(0)
      })
      this.goodsInfo.specList.forEach((specInfo, index) => {
        const children = []
        specInfo.valueList.forEach((child) => {
          children.push(child.value)
        })
        if (children.includes(specValue)) {
          specValues[index] = specValue
        } else {
          specValues[index] =
            this.specifications[index] == undefined
              ? 0
              : this.specifications[index]
        }
      })
      this.specifications = specValues
    },
    // 扫码加入购物车
    addToCart1(skuNo) {
      this.isSearch = false
      getGoodsList({
        brandId: this.$store.getters.storeId,
        categoryId: this.categoryId,
        page: this.page,
        size: this.pageSize,
        keyword: skuNo
      })
        // 扫码枪扫描商品条码，直接加入购物车
        // searchGoods({ keyword: skuNo })
        .then((response) => {
          this.loading = false
          console.log(response.data.data)
          if (response.data.data && response.data.data.goodsList.length == 1) {
            this.clickGoods(response.data.data.goodsList[0])
            this.isSearch = true
            this.searchForm.keyword = ""
            return false
          } else {
            // this.$alert("抱歉，未查询到商品信息！");
            return false
          }
        })
        .catch((err) => {
          this.loading = false
          console.log(err.toString())
        })
    },
    // 加入购物车
    addToCart() {
      if (this.loading || !this.goodsInfo.id || this.goodsNum <= 0) {
        return false
      }
      let productId = 0
      if (this.goodsInfo.productList?.length === 1) {
        const [productInfo] = this.goodsInfo.productList
        productId = productInfo.id
      }
      this.goodsInfo.productList.forEach((productInfo) => {
        if (productInfo.specifications.join() === this.specifications.join()) {
          productId = productInfo.id
        }
      })
      if (this.goodsInfo.productList.length && productId <= 0) {
        this.$alert("请先确认商品规格！")
        return false
      }
      // 添加到购物车
      const cartInfo = {
        brandId: this.$store.getters.storeId,
        goodsId: this.goodsInfo.id,
        productId: productId,
        number: this.goodsNum,
        userId: this.$store.getters.userId,
        vipUserId: this.memberInfo?.vipUserId
      }
      this.loading = true
      cartAdd(cartInfo)
        .then((response) => {
          this.loading = false
          if (response.data.data) {
            this.getCartList()
            this.openGoodsDialog = false
            this.specifications = []
            this.goodsNum = 0
            this.$nextTick(() => {
              this.$refs.inputRef.focus()
            })
          }
        })
        .catch((err) => {
          this.loading = false
          console.log(err.toString())
        })
    },
    // 删除购物车的商品
    removeFromCart(cartInfo) {
      cartDelete({
        productIds: [cartInfo.productId]
      })
        .then((response) => {
          if (response.data.data) {
            this.getCartList()
          }
        })
        .catch(() => {
          // empty
        })
    },
    // 购物车数量变化
    changeBuyNum(cartInfo) {
      this.loading = true
      cartUpdate({
        productId: cartInfo.productId,
        goodsId: cartInfo.goodsId,
        number: cartInfo.number,
        id: cartInfo.cartId
      })
        .then((response) => {
          this.loading = false
          if (response.data.data.cartId) {
            this.getCartList()
            this.openGoodsDialog = false
            this.specifications = []
          }
        })
        .catch(() => {
          this.loading = false
          this.getCartList()
        })
    },
    // 弹出关联会员
    switchMember(actionType) {
      this.actionType = actionType
      this.openMemberDialog = true
    },
    // 确认关联会员
    doSwitchMember(memberInfo) {
      this.openMemberDialog = false
      this.memberInfo = memberInfo
      if (memberInfo != null) {
        if (this.memberInfo && this.memberInfo.vipUserId) {
          setUserId(memberInfo.vipUserId)
          setMobile(memberInfo.mobile)
          // 切换为vip后
          updateCartVip({
            vipUserId: memberInfo.vipUserId
          }).then(() => {
            this.getCartList()
          })
        }
      } else {
        removeUserId()
        removeMobile()
        // 切换为非vip后
        updateCartVip({ vipUserId: "" }).then(() => {
          this.getCartList()
        })
      }
    },
    switchHeXiao() {
      this.openHeXiaoDialog = true
    },
    closeMemberDialog() {
      this.openMemberDialog = false
    },
    closeHeXiaoDialog() {
      this.openHeXiaoDialog = false
    },
    // 退出登录
    logout() {
      this.$router.push("/")
    },
    // 发起结算
    doSettlement() {
      if (this.cartList.length < 1) {
        this.$alert("请先添加结算商品！")
        return false
      }
      this.orderInfo = {}
      this.orderInfo.totalPrice = this.cartTotalPrice
      this.orderInfo.discountAmount =
        this.checkedAllGoodsAmount - this.cartTotalPrice
      this.orderInfo.checkedAllGoodsAmount = this.checkedAllGoodsAmount
      if (this.loading) {
        return false
      }
      this.openSettlementDialog = true
    },
    // 无商品结算
    doCashier() {
      this.orderInfo = {}
      this.openNoGoodsCashierDialog = true
    },
    // 提交结算
    submitCashier(param) {
      this.orderInfo = {}
      this.orderInfo.totalPrice = this.cartTotalPrice
      this.orderInfo.discountAmount =
        this.checkedAllGoodsAmount - this.cartTotalPrice
      this.openSettlementDialog = true
      this.cartTotalPrice = parseFloat(param.amount)
      this.cartRemark = param.remark
      this.openNoGoodsCashierDialog = false
    },
    // 确认结算
    submitSettlement(param) {
      if (this.loading) {
        return false
      }
      this.loading = true
      submitOrder({
        cartId: 0,
        payType: param.payType
      })
        .then((response) => {
          console.log("response123", response)
          if (response.data.errno != 0) {
            this.loading = false
            this.$alert(response.errmsg)
            return
          }
          this.loading = false
          this.doSwitchMember(null)
          this.initGoodsList()
          removeUserId()
          removeMobile()
          // 切换为非vip后
          updateCartVip({ vipUserId: "" }).then(() => {
            this.getCartList()
          })
          this.openSettlementDialog = false
          this.showPayResult({
            isSuccess: true,
            payAmount: this.orderInfo.totalPrice,
            orderId: response.data.data.orderId
          })
        })
        .catch((err) => {
          this.loading = false
          this.$alert(err.data.data.errmsg)
        })
    },
    // 关闭对话框
    closeDialog(dialog) {
      if (dialog == "settlementDialog") {
        this.openSettlementDialog = false
        // } else if (dialog == "scanPayCodeDialog") {
        //   this.openScanPayCodeDialog = false;
      } else if (dialog == "payResultDialog") {
        this.openPayResultDialog = false
      } else if (dialog == "printOrder") {
        this.openOrderPrintDialog = false
      } else if (dialog == "openNoGoodsCashierDialog") {
        this.openNoGoodsCashierDialog = false
      }
    },
    // 展示支付结果
    showPayResult(payResult) {
      this.payResult = payResult
      this.openPayResultDialog = true
    },

    // 打印小票
    showOrderPrint(orderId) {
      getOrderInfo({
        id: orderId
      })
        .then((response) => {
          this.orderInfo = response.data.data.order
          this.openOrderPrintDialog = true
          this.orderGoods = response.data.data.orderGoods
        })
        .catch((err) => {
          this.loading = false
        })
    },
    // 确认关闭
    handleClose() {
      return false
    },
    playSoundTwice() {
      // 确保音频文件路径正确
      const audioPath = require('@/assets/user-order-sound.mp3')
      const audio = new Audio(audioPath)

      const playPromise = audio.play()

      if (playPromise !== undefined) {
        playPromise.then(() => {
          // 第一次播放成功后，等待 1 秒再播放第二次
          setTimeout(() => {
            audio.play().catch(error => {
              console.error('第二次播放声音失败:', error)
            })
          }, 6000)
        }).catch(error => {
          console.error('第一次播放声音失败:', error)
        })
      } else {
        // 对于不支持 promise 的浏览器
        audio.play()
        setTimeout(() => {
          audio.play().catch(error => {
            console.error('第二次播放声音失败:', error)
          })
        }, 6000)
      }
    },
    getTransmitOrders() {
      transmitNotify().then((res) => {
        let orders = res.data.data
        console.log("getTransmitOrders", orders)
        if (!orders || orders.length == 0) {
          return
        }
        let str = "共有" + orders.length + "个订单待处理"
        const notify = this.$notify({
          title: "您有新的订单请及时处理",
          message: str,
          position: "bottom-right",
          duration: 59500,
          type: "warning",
          dangerouslyUseHTMLString: true, // 允许使用HTML字符串
          onClick: () => {
            // 点击通知时的回调函数
            this.$router.push({
              path: "/cashier/transmitOrder",
              name: "transmitOrder"
            })
            notify.close()
          }
        })
        // 播放声音两次
        this.playSoundTwice()

      })
    },
    getVipInfo(mobile) {
      getMemberInfo({ mobile: mobile })
        .then((response) => {
          console.log(response)
          if (response.data.data.vipUserId) {
            this.memberInfo.points = response.data.data.points
            this.memberInfo.mobile = mobile
            this.memberInfo.vipUserId = response.data.data.vipUserId
          }
        })
        .catch((res) => {
          this.$alert(res.data.errmsg)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.home-container {
  height: 100%;
  flex-grow: 1;
  display: flex;
  flex-direction: row;
  position: relative;

  .pagination {
    position: absolute;
    bottom: 5px;
    height: 30px;
    min-width: 500px;
    line-height: 30px;
    left: 10px;
    margin-top: 10px;
    display: block;
    color: #ffffff;
    border-radius: 5px;
    z-index: 1000;
  }

  .cart-container {
    width: 350px;
    height: 100%;
    background: #ffffff;
    border: #cccccc solid 1px;
    display: flex;
    flex-direction: column;

    .cart-title {
      height: 70px;
      width: 350px;
      background: #00acac;
      border-bottom: #cccccc 2px solid;
      color: #ffffff;
      padding-top: 16px;
      padding-left: 1px;
      display: block;
      position: relative;
      clear: both;

      .logo {
        float: left;
        font-size: 24px;

        .avatar {
          width: 30px;
          height: 30px;
          border-radius: 40px;
          margin: 5px 0px 5px 5px;
        }
      }

      .member-info {
        float: left;
        margin-top: 5px;

        .name {
          margin-left: 2px;
          margin-right: 3px;
        }

        .none {
          margin-left: 2px;
          margin-right: 5px;
          font-size: 13px;
        }

        .switch {
          padding: 8px 8px 8px 4px;
        }
      }
    }

    .cart-list {
      flex-grow: 1;
      width: 350px;
      color: #666666;
      overflow-y: auto;
      overflow-x: hidden;
      display: flex;
      flex-direction: column;
      list-style-type: none;
      padding: 0;

      .cart-item {
        border-bottom: dashed 1px #cccccc;
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 110px;
        padding: 2px 5px;

        .cart-item-header {
          display: flex;
          flex-direction: row;
          width: 100%;

          .cart-image {
            width: 60px;
            height: 60px;
            object-fit: contain;
            border-radius: 5px;
            border: solid 1px #ccc;
          }

          .cart-name {
            display: flex;
            flex-direction: column;
            flex-grow: 1;
            padding: 2px;

            .name {
              font-weight: bold;
              font-size: 13px;
              flex-grow: 1;
              max-height: 30px;
              overflow: hidden;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
            }

            .code {
              font-size: 12px;
              flex-grow: 1;
              max-height: 30px;
              overflow: hidden;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
            }

            .spec {
              font-size: 12px;
              height: 20px;
              margin-top: 2px;

              .item {
                margin-right: 2px;
                border-radius: 5px;
                text-align: center;
                max-width: 50px;
                height: 20px;
                line-height: 20px;
                float: left;
                display: block;
                overflow: hidden;
                color: #606266;
                cursor: pointer;
                background: #cceeee;
                padding: 0px 3px 0px 3px;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
            }
          }

          .cart-delete {
            padding: 0;
            width: 50px;
            height: 39px;
            margin-left: 5px;
          }
        }

        .cart-item-option {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          margin: 5px 0;
          flex-grow: 1;
          width: 100%;

          .input {
            width: 250px;
            margin-right: 20px;
          }
        }
      }
    }

    .empty {
      flex-grow: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .footer {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      background: #00acac;
      padding: 10px 0;
      color: #ffffff;
      position: relative;
      border: solid 3px #cccccc;

      .number {
        font-size: 13px;
        display: flex;
        flex-direction: column;

        .total-price {
          .num {
            color: #ff5b57;
            font-size: 18px;
          }
        }
      }

      .options {
        text-align: center;
        cursor: pointer;
        color: #ffffff;

        .submit {
          height: 50px;
          border: solid 1px #ff5b57;
          width: 135px;
          border-radius: 5px;
          background: #ff5b57;
          font-weight: bold;
        }
      }
    }
  }

  .main-list {
    height: 100%;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    position: relative;

    .search-box {
      height: 106px;
      min-width: 800px;
      background: #ffffff;
      padding: 5px;
      color: red;

      .search-form {
        height: 50px;

        .form-item {
          margin-right: -2px;
        }

        .input-item {
          min-width: 400px;
        }

        .search-goods {
          height: 50px;
          background: #00acac;
          margin-left: 3px;
          color: #fff;
        }

        .setting {
          float: right;
          margin-right: 20px;

          .item {
            margin-left: 15px;
            color: #2b2f3a;
            cursor: pointer;
          }

          .active {
            font-weight: bold;
            color: #2b2f3a;
          }

          .icon {
            width: 14px;
            height: 14px;
            vertical-align: middle;
            margin-right: 2px;
          }

          .text {
            font-size: 14px;
            display: inline-block;
            vertical-align: middle;
          }
        }
      }

      .tab-box {
        margin-top: 3px;
        width: 100%;
      }
    }

    .goods-list {
      flex-grow: 1;
      scrollbar-width: none;
      overflow-y: auto;
      margin-left: 2px;
      margin-bottom: 42px;
      display: flex;
      flex-wrap: wrap;
      flex-direction: row;
      align-content: flex-start;

      .el-empty {
        width: 100%;
      }

      .goods-item {
        //width: 156px;
        min-height: 100px;
        padding: 1px;
        background: #ffffff;
        text-align: left;
        cursor: pointer;

        .item {
          //width: 150px;
          background: #ffffff;
          padding: 2px;
          border-radius: 4px;
          border: solid 1px #cccccc;
          margin: 0px;
          text-align: center;

          .goods-name {
            margin-top: 6px;
            font-size: 12px;
            margin-left: 4px;
            text-align: left;
            color: #666666;
            height: 20px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }

          .goods-price-list {
            margin-left: 4px;
            font-size: 12px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;

            .bold {
              font-weight: bold;
            }

            .red {
              color: #ff5b57;
            }

            .gray {
              color: gray;
            }

            .line-through {
              text-decoration: line-through;
            }
          }

          .image {
            max-width: 100px;
            min-width: 100px;
            height: 100px;
            object-fit: contain;
            border-radius: 3px;
          }
        }
      }
    }
  }
}

.goods-info {
  border: solid 1px #ccc;
  padding: 30px;
  border-radius: 5px;

  .name {
    height: auto;
    font-weight: bold;
    font-size: 20px;
  }

  .price {
    margin-top: 8px;
    height: 40px;
    color: #ff5b57;
    font-size: 16px;
  }

  .spec-list {
    border: solid 1px #ccc;
    padding: 20px;
    margin-top: 10px;
    border-radius: 6px;

    .spec-item {
      margin-bottom: 20px;

      .spec-name {
        font-weight: bold;
        font-size: 16px;
      }

      .values {
        font-size: 12px;

        .value {
          border: solid 1px #cceeee;
          margin: 5px;
          padding: 8px 15px 5px 15px;
          cursor: pointer;
          border-radius: 4px;
          background: rgba(0, 172, 172, 0.1);
          color: #666666;
          float: left;
        }

        .active {
          border: solid 1px #ff5891;
          background: #ff5b57;
          color: #ffffff;
        }
      }
    }
  }
}

.common-dialog {
  .el-dialog {
    border: solid 0px #00acac;
  }

  .el-dialog__header {
    background: #00acac;
    padding: 10px;
  }

  .el-dialog__headerbtn {
    top: 15px;
  }

  .el-dialog__body {
    padding: 30px;
  }

  .el-dialog__title,
  .el-dialog__close {
    color: #fff;
    font-size: 14px;
  }

  .el-dialog__title,
  .el-dialog__close:hover {
    color: #fff;
    font-weight: bold;
  }
}
</style>
<style scoped>
.input-item >>> .el-input__inner {
  border: #00acac solid 2px;
  line-height: 50px;
  height: 50px;
}

.form-item >>> .el-form-item__label {
  line-height: 50px;
  height: 50px;
}

.el-tabs--border-card {
  box-shadow: none;
  border: none;
}

::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 0px;
}
</style>
